package com.credithc.signature.facade.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

@Slf4j
public class FileUtil {

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(@RequestParam MultipartFile file) {
        File toFile = null;
        if (!"".equals(file) && file.getSize() > 0) {
            try {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
                inputStreamToFile(ins, toFile);
                ins.close();
            } catch (Exception e) {
                log.error("工具类ManagerFileUtil[multipartFileToFile]方法发生异常", e);
            }
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            log.error("工具类ManagerFileUtil[inputStreamToFile]方法发生异常", e);
        }
    }
}
